<?php
// 接口-库存余额
namespace interface\v1;

class inventoryOtherClass extends index
{
    private const        page = 'inventoryBalance';
    private const        table = 'inventory_record';
    private const        tableInv = 'inventory';
    private const        tableInvMx = 'inventory_detail';
    private const        title = '库存余额';

    /**
     * 账套列表
     *
     * @return void
     */
    public function company(): void
    {
        $this->code = 1;
        $result = find(['table' => 'company', 'field' => 'coid as value, name as text']);
        $this->resp['data'] = [
            'option' => $result['array'],
            'now'    => self::findCoid(),
        ];
    }

    /**
     * 查找当前使用的coid
     *
     * @return mixed
     */
    public static function findCoid(): mixed
    {
        $record = query('user_setting', "stid = '" . self::$stid . "' and type = '当前使用账套'");
        if (empty($record['id'])) {
            $company = query('company', "isDel = 0");
            self::updateCoidRecord($company['coid']);
            self::$coid = $company['coid'];
            return $company['coid'];
        }
        return $record['value'];
    }

    /**
     * 记录当前使用的账套
     */
    public static function updateCoidRecord($coid): bool
    {
        if (empty($coid)) {
            return false;
        }
        $record = query('user_setting', "stid = '" . self::$stid . "' and type = '当前使用账套'");
        if (empty($record['id'])) {
            $warn = static::insert(array(
                'table' => 'user_setting',
                'field' => [
                    'type'  => '当前使用账套',
                    'value' => $coid,
                    'stid'  => self::$stid,
                ],
            ));
        } else {
            $warn = static::update(array(
                'table' => 'user_setting',
                'field' => [
                    'value' => $coid,
                ],
                'where' => "id = '$record[id]'",
            ));
        }
        return in_array($warn, ['新增成功', '更新成功']);
    }

    /**
     * 切换账套
     *
     * @return void
     */
    public function setCompany(): void
    {
        $coid = $this->post('coid');
        if (!$coid) {
            $this->resp['warn'] = '请选择账套';
        } else {
            $bool = self::updateCoidRecord($coid);
            if ($bool !== true) {
                $this->resp['warn'] = '账套选择失败';
            } else {
                $this->resp['warn'] = '选择成功';
                $this->code = 1;
            }
        }
    }

    /**
     * 列表仓库
     *
     * @return void
     */
    public function warehouse(): void
    {
        $this->code = 1;
        if (empty(self::$coid)) {
            self::$coid = self::findCoid();
        }
        $result = find(['table' => 'warehouse', 'field' => 'id as value, name as text', 'where' => " state = '启用' AND coid = '" . self::$coid . "' "]);
        $this->resp['data'] = $result['array'];
    }

    /**
     * 供应商
     *
     * @return void
     */
    public function supplier(): void
    {
        $this->code = 1;
        $result = find(['table' => 'supplier', 'field' => 'id as value, name as text', 'where' => "state = '启用' AND coid = '" . self::$coid . "' "]);
        $this->resp['data'] = $result['array'];
    }

    /**
     * 获取往来单位
     *
     * @return bool|string
     */
    public function getTarget(): void
    {
        $val          = $this->post('keyword');//关键词
        $where        = $where2 = '';
        if (!empty($val)) {
            $where  = " and (companyName like '%" . $val . "%' or orderNo like '%" . $val . "%')";
            $where2 = " and (name like '%" . $val . "%' or code like '%" . $val . "%')";
        }
        $this->code = 1;
        $this->resp['data'] = self::sqlFind(" select khid as value,concat(orderNo,'-',companyName) as text from kehu where coid = '" . self::$coid . "' {$where} UNION ALL select id as value,concat(code,'-',name) as text from supplier where coid = '" . self::$coid . "' {$where2} ");
    }

    /**
     * 加工单类型
     *
     * @return void
     */
    public function machiningType(): void
    {
        $this->code = 1;
        $this->resp['data'] = ['生产加工', '生产返工'];
    }

    /**
     * 客户
     *
     * @return void
     */
    public function kehu(): void
    {
        $this->code = 1;
        $result = find(['table' => 'kehu', 'field' => 'khid as value, companyName as text', 'where' => " coid = '" . self::$coid . "'"]);
        $this->resp['data'] = $result['array'];
    }

    /**
     * 选择员工
     */
    public function staff()
    {
        $this->code = 1;
        $result = find([
            'field' => 'stid as value, name as text',
            'table' => 'staff',
        ]);
        $this->resp['data'] = $result['array'];
    }

    /**
     * 物料分类
     *
     * @return void
     */
    public function materialType(): void
    {
        $this->code = 1;
        $result = find([
            'table' => 'material_type',
            'field' => " id as value, name as text ",
            'where' => generateWhere([
                'coid' => self::$coid,
            ]),
        ]);
        $this->resp['data'] = $result['array'];
    }

    /**
     * 物料品牌
     *
     * @return void
     */
    /*public function materialBrand(): void
    {
        $this->code = 1;
        $result = find([
            'table' => 'material',
            'field' => "DISTINCT(brand) as text, id as value ",
            'where' => generateWhere([
                    'coid'  => self::$coid,
                    'state' => '启用',
                ]) . " AND brand <> '' ",
        ]);
        $this->resp['data'] = $result['array'];
    }*/

    /**
     * 选择生产线
     *
     * @return void
     */
    public function line(): void
    {
        $this->code = 1;
        $where = search([
            '=' => [
                'workshop' => $this->post('workshop') ?: '',
            ],
        ]);
        $field = $where ? ' id as value, name as text ' : 'distinct workshop as text';
        $result = find([
            'table' => 'product_line',
            'field' => $field,
            'where' => generateWhere([
                'coid'  => self::$coid,
                'state' => '启用',
            ]) . $where,
        ]);
        $this->resp['data'] = $result['array'];
    }

    /**
     * 待办数量
     *
     * @return void
     */
    public function backlog(): void
    {
        $this->code = 1;
        $this->resp['data'] = [
            'backlog' => self::total([
                'table' => 'backlog',
                'where' => " stid = '" . self::$stid . "' AND workFlow = '待处理' AND startDay <='" . $this->date . "' ",
            ]),
            'message' => self::total([
                'table' => 'message',
                'where' => " stid = '" . self::$stid . "' AND see = '否' ",
            ]),
        ];
    }

    /**
     * 待办list
     *
     * @return void
     */
    public function backlogList(): void
    {
        $this->code = 1;
        $act = $this->post('act');
        $result = match ($act) {
            default   => $this->page([
                'table' => 'backlog',
                'where' => " stid = '" . self::$stid . "' AND workFlow = '待处理' AND startDay <='" . $this->date . "' ",
                'order' => 'time desc',
            ]),
            'message' => $this->page([
                'table' => 'message',
                'where' => " stid = '" . self::$stid . "' AND see = '否' ",
                'order' => 'time desc',
            ])
        };
        $this->resp['data'] = [
            'result' => $result['array'],
            'page'   => $result['para'],
        ];
    }

    public function dataBoard()
    {
        /**
         * 金额单位格式化
         *
         * @param $money
         * @return string
         */
        function moneyUnit($money): string
        {
            return $money > 10000 ? round(($money / 10000), 2) . '万' : round($money, 2);
        }
        function numTimeline($detail_data): array
        {
            $groupedByDate = ['year'=>0,'month'=>0,'day'=>0];
            $year_now = date('Y');
            $month_now = date('m');
            $day_now = date('d');
            foreach ($detail_data as $item) {
                $year = date('Y', strtotime($item['recordDate']));
                $month = date('m', strtotime($item['recordDate']));
                $day = date('d', strtotime($item['recordDate']));
                // 创建一个多维数组来存储年、月、日分组的数据
                if($year_now == $year){
                    $groupedByDate['year'] += $item['num'] ?? 1;
                }
                if ($month_now == $month){
                    $groupedByDate['month'] += $item['num'] ?? 1;
                }
                if ($day_now == $day){
                    $groupedByDate['day'] += $item['num'] ?? 1;
                }
            }
            return $groupedByDate;
        }
        $this->code = 1;
        $purchase_apply_array = $sale_order_array = $steel_cylinder_detail_array = $steel_cylinder_array = [];
        if ($this->power('salesReportForm', 'see')) {
            //采购数量-大宗物资
            $purchase_apply =  find(array('table' => "purchase_apply_detail as a join purchase_apply as b on a.orderId = b.id", "where" => " b.goods_type = '大宗物资' and b.state = '已通过' and YEAR(recordDate) = '".date("Y")."' ", 'field' => "a.id,b.recordDate,a.num"));
            $purchase_apply_array = numTimeline($purchase_apply['array']);
            //销售发货单数量
            $sale_order =  find(array('table' => "sale_order_detail as a join sale_order as b on a.orderId = b.id", "where" => " b.state = '已确认' and YEAR(recordDate) = '".date("Y")."' ", 'field' => "a.id,b.recordDate,a.num"));
            $sale_order_array = numTimeline($sale_order['array']);
            //充装数量
            $steel_cylinder_detail =  find(array('table' => "steel_cylinder_detail", "where" => "YEAR(jsonData->'$.DT_ADD_END') = '".date("Y")."' and (jsonData->'$.N_AFTER' > 0)  ", 'field' => "jsonData->'$.DT_ADD_END' as recordDate,id"));
            $steel_cylinder_detail_array = numTimeline($steel_cylinder_detail['array']);
            //库存数量
            $steel_cylinder =  find(array('table' => "steel_cylinder", "where" => "YEAR(endTime) = '".date("Y")."' and type_cylinder = 2  ", 'field' => "endTime as recordDate,id"));
            $steel_cylinder_array = numTimeline($steel_cylinder['array']);
        }
        //进销存情况
        $this->resp['data'] = [
            [
                'type'  => '采购数量-当日',//大宗物资
                'money' => $purchase_apply_array['day'],
            ],
            [
                'type'  => '采购数量-当月',//大宗物资
                'money' => $purchase_apply_array['month'],
            ],
            [
                'type'  => '采购数量-当年',//大宗物资
                'money' => $purchase_apply_array['year'],
            ],
            [
                'type'  => '销售数量-当日',//取销售发货单数量
                'money' => $sale_order_array['day'],
            ],
            [
                'type'  => '销售数量-当月',//取销售发货单数量
                'money' => $sale_order_array['month'],
            ],
            [
                'type'  => '销售数量-当年',//取销售发货单数量
                'money' => $sale_order_array['year'],
            ],
            [
                'type'  => '充装数量-当日',//充装数量
                'money' => $steel_cylinder_detail_array['day'],
            ],
            [
                'type'  => '充装数量-当月',//充装数量
                'money' => $steel_cylinder_detail_array['month'],
            ],
            [
                'type'  => '充装数量-当年',//充装数量
                'money' => $steel_cylinder_detail_array['year'],
            ],
            [
                'type'  => '库存数量-当日',//库存数量
                'money' => $steel_cylinder_array['day'],
            ],
            [
                'type'  => '库存数量-当月',//库存数量
                'money' => $steel_cylinder_array['month'],
            ],
            [
                'type'  => '库存数量-当年',//库存数量
                'money' => $steel_cylinder_array['year'],
            ],
        ];
    }


    public function menu()
    {
        $imgSrc = root . 'img/miniProgram/erp/';
        $crmImgSrc     = root . 'img/miniProgram/crm/';
        $oaImgSrc     = root . 'img/miniProgram/oa/';
        $equipmentImgSrc     = root . 'img/miniProgram/equipment/';
        $items['人力资源'] = [
            'workSignAdd'     => [
                'name'  => '补卡申请',
                'icon'   => $oaImgSrc.'workSignAdd.png',
                'power' => 'workSignAdd',
                'url'   => '/oa/pages/workSignAdd/workSignAdd',
            ],
            'work' => [
                'name'  => '请假申请',
                'icon'   => $oaImgSrc.'holiday.png',
                'power' => 'work',
                'url'   => '/oa/pages/workHoliday/workHoliday',
            ],
            'workOut'  => [
                'name'  => '外出申请',
                'icon'   => $oaImgSrc.'out.png',
                'power' => 'workOut',
                'url'   => '/oa/pages/workOut/workOut',
            ],
            "workAdd"     => [
                'name'  => '加班申请',
                'icon'   => $oaImgSrc.'workAdd.png',
                'power' => 'workAdd',
                'url'   => '/oa/pages/work/work',
            ],
//            'workReportDay'  => [
//                'name'  => '日报',
//                'icon'   => $oaImgSrc.'dayReport.png',
//                'power' => 'workReportDay',
//                'url'   => '/oa/pages/dayReportEdit/dayReportEdit',
//            ],
//            'workReportWeek'  => [
//                'name'  => '周报',
//                'icon'   => $oaImgSrc.'weekReport.png',
//                'power' => 'workReportWeek',
//                'url'   => '/oa/pages/weekReportEdit/weekReportEdit',
//            ],
//            'workReportMonth'  => [
//                'name'  => '月报',
//                'icon'   => $oaImgSrc.'monthReport.png',
//                'power' => 'workReportMonth',
//                'url'   => '/oa/pages/monthReportEdit/monthReportEdit',
//            ],
//            'beTested'  => [
//                'name'  => '考试',
//                'icon'   => $oaImgSrc.'examine.png',
//                'power' => 'beTested',
//                'url'   => '/oa/pages/exam/exam',
//            ],
            'workSign'  => [
                'name'  => '考勤',
                'icon'   => $oaImgSrc.'clock.png',
                'power' => 'workSign',
                'url'   => '/oa/pages/clock/clock',
            ],
            'paySlip'  => [
                'name'  => '工资条',
                'icon'   => $oaImgSrc.'payslip.png',
                'power' => 'paySlip',
                'url'   => '/oa/pages/paySlip/paySlip',
            ],
            'initiateApproval'  => [
                'name'  => '审批',
                'icon'   => $oaImgSrc.'audit.png',
                'power' => 'initiateApproval',
                'url'   => '/oa/pages/audit/audit',
            ],
//            'workReport'  => [
//                'name'  => '汇报',
//                'icon'   => $oaImgSrc.'report.png',
//                'power' => 'workReport',
//                'url'   => '/oa/pages/workReport/workReport',
//            ],
        ];
//        $items['行政管理'] = [
//            'canteen'     => [
//                'name'  => '食堂',
//                'icon'   => $oaImgSrc.'diningHall.png',
//                'url'   => '/oa/pages/canteen/canteen',
//                'power' => 'canteen',
//            ],
//            'dormitory' => [
//                'name'  => '宿舍',
//                'icon'   => $oaImgSrc.'payment.png',
//                'url'   => '/oa/pages/dormitory/dormitory',
//                'power' => 'dormitory',
//            ],
//            'checkLiveRecord'  => [
//                'name'  => '查寝',
//                'icon'   => $oaImgSrc.'workSignAdd.png',
//                'url'   => '/oa/pages/checkLiveRecord/checkLiveRecord',
//                'power' => 'checkLiveRecord',
//            ]
//        ];
        $items['销售管理'] = [
            // crm
            'client'     => [
                'name' => '客户',
                'icon' => $crmImgSrc . 'client.svg',
                'power' => 'client',
                'url'  => '/crm/pages/client/client',
            ],
//            'clientPool' => [
//                'name' => '公客池',
//                'icon' => $crmImgSrc . 'publicClient.svg',
//                'power' => 'clientPool',
//                'url'  => '/crm/pages/publicClient/publicClient',
//            ],
//            'kehuStaff'  => [
//                'name' => '联系人',
//                'icon' => $crmImgSrc . 'contacts.svg',
//                'power' => 'kehuStaff',
//                'url'  => '/crm/pages/contacts/contacts',
//            ],
//            "follow"     => [
//                'name' => '跟进记录',
//                'icon' => $crmImgSrc . 'follow.svg',
//                'power' => 'follow',
//                'url'  => '/crm/pages/follow/follow',
//            ],
//            'visitPlan'  => [
//                'name' => '访客计划',
//                'icon' => $crmImgSrc . 'visitPlan.svg',
//                'power' => 'visitPlan',
//                'url'  => '/crm/pages/visitPlan/visitPlan',
//            ],
            'saleOrder'           => [
                'name' => '销售订单',
                'icon' => $imgSrc . 'sales.svg',
                'power' => 'saleOrder',
                'url'  => '/packageA/pages/sales/index',
            ],
            'saleSendOrder'           => [
                'name' => '销售发货订单',
                'icon' => $imgSrc . 'sales.svg',
                'power' => 'saleOrder',
                'url'  => '/packageA/pages/saleSendOrder/index',
            ],
            'customerStorage'           => [
                'name' => '客户寄存订单',
                'icon' => $imgSrc . 'sales.svg',
                'power' => 'saleOrder',
                'url'  => '/packageA/pages/customerStorage/index',
            ],
            'salesReportForm'     => [
                'name' => '销售统计',
                'icon' => $imgSrc . 'saleStatistics.svg',
                'power' => 'salesReportForm',
                'url'  => '/pages/saleStatistics/index',
            ],
        ];
        $items['采购管理'] = [
            'purchaseReportForm'  => [
                'name' => '采购统计',
                'icon' => $imgSrc . 'purchaseStatistics.svg',
                'power' => 'purchaseReportForm',
                'url'  => '/packageB/pages/purchaseStatistics/index',
            ],
        ];
        $items['库存管理'] = [
            'inStock'             => [
                'name' => '待入库',
                'icon' => $imgSrc . 'instock.svg',
                'power' => 'inStock',
                'url'  => '/packageA/pages/instock/wait',
            ],
            'inStockExec'             => [
                'name' => '入库',
                'icon' => $imgSrc . 'instock.svg',
                'power' => 'inStockExec',
                'url'  => '/packageA/pages/instock/index',
            ],
            'outStock'            => [
                'name' => '待出库',
                'icon' => $imgSrc . 'outstock.svg',
                'power' => 'outStock',
                'url'  => '/packageA/pages/outstock/wait',
            ],
            'outStockExec'            => [
                'name' => '出库',
                'icon' => $imgSrc . 'outstock.svg',
                'power' => 'outStockExec',
                'url'  => '/packageA/pages/outstock/index',
            ],
            /*"moveStock"           => [
                "name" => "移库",
                'icon' => $imgSrc . 'moveStock.svg',
                'power' => 'moveStock',
                'url'  => '/packageA/pages/moveStock/index',
            ],*/
            'inspectSteelCylinder'    => [
                'name' => '待质检钢瓶',
                'icon' => $imgSrc . 'inventoryQuery.svg',
                'url'  => '/pages/cylinder/index',
            ],
            'inspectSteelCylinderLog'    => [
                'name' => '质检中钢瓶',
                'icon' => $imgSrc . 'inventoryQuery.svg',
                'url'  => '/pages/cylinderwait/index',
            ],
            'inventoryBalance'    => [
                'name' => '库存查询',
                'icon' => $imgSrc . 'inventoryQuery.svg',
                'power' => 'inventoryBalance',
                'url'  => '/pages/inventory/index',
            ],
            //            要打改，先隐藏
//            'inventoryReportForm' => [
//                'name' => '库存统计',
//                'icon' => $imgSrc . 'inventoryStatistics.svg',
//                'url'  => '/packageB/pages/inventoryStatistics/index',
//            ],
        ];
//        $items['自制生产'] = [
//            'processReport'       => [
//                'name' => '工序报工',
//                'icon' => $imgSrc . 'processReport.svg',
//                'power' => 'processReport',
//                'url'  => '/packageC/pages/processReport/index',
//            ],
//            'machiningOrder'      => [
//                'name' => '生产统计',
//                'icon' => $imgSrc . 'machiningStatistics.svg',
//                'power' => 'machiningOrder',
//                'url'  => '/packageB/pages/machiningStatistics/index',
//            ],
//        ];
        $items['设备管理'] = [
            'equipment'       => [
                'name' => '设备',
                'icon' => $equipmentImgSrc . 'equipment.svg',
                'power' => 'equipment',
                'url'  => '/equipment/pages/equipment/index',
            ],
//            'equipmentInspection'      => [
//                'name' => '设备巡检',
//                'icon' => $equipmentImgSrc . 'equipmentInspection.svg',
//                'power' => 'equipmentInspection',
//                'url'  => '/equipment/pages/inspection/index',
//            ],
        ];
//        $items['质量管理'] = [
//            'materialInspection'  => [
//                'name' => '来料检验',
//                'icon' => $imgSrc . 'materialInspection.svg',
//                'power' => 'materialInspection',
//                'url'  => '/packageC/pages/materialInspection/index',
//            ],
//            "outsourceInspection" => [
//                "name" => "委外入库检验",
//                'icon' => $imgSrc . 'outsourceInspection.svg',
//                'power' => 'outsourceInspection',
//                'url'  => '/packageC/pages/outsourceInspection/index',
//            ],
//            'processInspection'   => [
//                'name' => '制终检验',
//                'icon' => $imgSrc . 'processInspection.svg',
//                'power' => 'processInspection',
//                'url'  => '/packageC/pages/processInspection/index',
//            ],
//            'processingInspection'   => [
//                'name' => '制程检验',
//                'icon' => $imgSrc . 'processingInspection.svg',
//                'power' => 'processingInspection',
//                'url'  => '/packageC/pages/processingInspection/index',
//            ],
//            'shippingInspection'  => [
//                'name' => '发货检验',
//                'icon' => $imgSrc . 'shippingInspection.svg',
//                'power' => 'shippingInspection',
//                'url'  => '/packageC/pages/shippingInspection/index',
//            ],
//            'quarantine'          => [
//                'name' => '质检统计',
//                'icon' => $imgSrc . 'quarantineStatistics.svg',
//                'power' => 'quarantine',
//                'url'  => '/packageB/pages/quarantineStatistics/index',
//            ],
//        ];
        $items['财务管理'] = [
            'feeApply'     => [
                'name'  => '费用申请',
                'icon'   => $oaImgSrc.'feeApply.png',
                'power' => 'feeApply',
                'url'   => '/oa/pages/feeApply/feeApply',
            ],
            'cost' => [
                'name'  => '报销申请',
                'icon'   => $oaImgSrc.'cost.png',
                'power' => 'cost',
                'url'   => '/oa/pages/cost/cost',
            ],
            'payment'  => [
                'name'  => '付款申请',
                'icon'   => $oaImgSrc.'payment.png',
                'power' => 'payment',
                'url'   => '/oa/pages/payment/payment',
            ],
            'costIndex'          => [
                'name' => '报销统计',
                'icon' => $imgSrc . 'quarantineStatistics.svg',
                'power' => 'costIndex',
                'url'  => '/oa/pages/cost/index',
            ],
        ];
        return $items;
    }
    public function func()
    {
        $this->code = 1;
        $items = $this->menu();
        $array = [];
        $whiteList = ['workReport','costIndex'];
        foreach ($items as $title => $pages) {
            $temp = [];
            foreach ($pages as $page => $item) {
                if (in_array($page, $whiteList) || $this->power($page, 'see')) {
                    $temp[] = $item;
                }
            }
            if (empty($temp)) {
                continue;
            }
            $array[] = [
                'title' => $title,
                'array' => $temp,
            ];
        }
        $this->resp['data'] = $array;
    }

    public function getDefaultFunc()
    {
        $this->code = 1;
        $this->resp['data'] = [];
        $record = query('user_setting', "stid = '" . self::$stid . "' and type = 'ERP小程序常用功能'");
        if (!empty($record['id'])) {
            $this->resp['data'] = json_decode($record['value'], true);
        } else {
            static::insert(array(
                'table' => 'user_setting',
                'field' => [
                    'coid'  => self::$coid,
                    'type'  => 'ERP小程序常用功能',
                    'value' => '{}',
                    'stid'  => self::$stid,
                ],
            ));
        }
        // 没有设置常用功能，追加四个默认功能
        if(!$this->resp['data']){
            $items = $this->menu();
            $whiteList = ['workReport'];
            foreach ($items as $title => $pages) {
                foreach ($pages as $page => $item) {
                    if (in_array($page, $whiteList) || $this->power($page, 'see')) {
                        $this->resp['data'][] = $item;
                    }
                    if (count($this->resp['data']) == 4) {
                        break 2;
                    }
                }
            }
        }
    }

    /**
     * 更新默认功能
     */
    public function upDefaultFunc()
    {
        $value = $_POST['func'] ?: '';
        $array = json_decode($value, true);
        if (!is_array($array)) {
            $this->resp['warn'] = '更新失败';
        } else {
            $func = json_encode($array ?: [], 320);
            $record = query('user_setting', "stid = '" . self::$stid . "' and type = 'ERP小程序常用功能'");
            if (empty($record['id'])) {
                $warn = static::insert(array(
                    'table' => 'user_setting',
                    'field' => [
                        'type'  => 'ERP小程序常用功能',
                        'value' => $func,
                        'stid'  => self::$stid,
                    ],
                ));
            } else {
                $warn = static::update(array(
                    'table' => 'user_setting',
                    'field' => [
                        'value' => $func,
                    ],
                    'where' => "id = '$record[id]'",
                ));
            }
            if (in_array($warn, ['新增成功', '更新成功'])) {
                $this->resp['warn'] = '更新成功';
                $this->resp['data'] = $array;
                $this->code = 1;
            } else {
                $this->resp['warn'] = '更新失败';
            }
        }
    }

    /**
     * 查找物料
     *
     * @return void
     */
    public function codeByMaterial(): void
    {
        $code = $this->post('code') ?: '';
        $id = $this->post('orderId') ?: '';
        $waid = $this->post('waid') ?: '';
        $from = $this->post('from') ?: '';
        if (self::isNull($code)) {
            $this->resp['warn'] = '物料条码不能为空';
        } else {
            $material = query('material', " coid = '" . self::$coid . "' AND barcode = '$code' ");
            if (self::isNull($material['id'])) {
                $this->resp['warn'] = '当前账套不存在该物料，请确认';
                return;
            }
            $inventoryNum = inventoryBalanceClass::inventoryNum($material['id'], $waid);
            $result = [
                'mxId'          => self::getId(),
                'materialId' => $material['id'],
                'code'          => $material['code'],
                'name'          => $material['name'],
                'model'         => $material['model'],
                'unit'          => $material['unit'],
                'unitOption'    => inventoryBalanceClass::materialUnit($material['id']),
            ];
            $info = [];
            if ($id && $from) {
                switch ($from) {
                    case '入库单':
                    case '出库单':
                        $table = 'inventory';
                        $info = query($table, " id = '$id' ", 'id, orderNo, IFNULL(orderDate, time) as orderDate, classify, targetId, text');
                        if ($info['classify'] == 0) {
                            $info['target'] = query('kehu', " khid = '{$info['targetId']}' ")['companyName'];
                        } else {
                            $info['target'] = query('supplier', " id = '{$info['targetId']}' ")['name'];
                        }
                        break;
                    case '盘点单':
                        $table = 'inventory_take';
                        $info = query($table, " id = '$id' ", 'id, orderNo, warehouse, type as typeId, orderDate, text');
                        $info['mtype'] = $info['typeId'] ? inventoryClass::getTypeName($info['typeId']) : null;
                        unset($info['typeId']);
                        break;
                    case '调拨单':
                        $table = 'inventory_allot';
                        $info = query($table, " id = '$id' ", 'id, orderNo, outWarehouse, inWarehouse, orderDate');
                        break;
                    default:
                        $this->resp['warn'] = '类型错误';
                        return;
                }

                if (self::isNull($info['id'])) {
                    $this->resp['warn'] = '此订单信息不存在';
                    return;
                }
                $detail = query($table . '_detail', " orderId = '{$info['id']}' AND materialId = '$material[id]' ");
                if (self::isNull($detail['id'])) {
                    $this->resp['warn'] = '该订单不存在此物料信息';
                    return;
                }
                $result['mxId'] = $detail['id'];
                $result = array_merge($result, [
                    'num'          => $detail['num'],
                    'inventoryNum' => $inventoryNum,
                    'orderNum'     => $detail['orderNum'] ?: 0,
                ]);
            }
            $this->resp['data'] = [
                'info'   => $info,
                'result' => $result,
            ];
            $this->code = 1;
        }
    }

    /**
     * 查找单号
     *
     * @return void
     */
    public function orderByNo(): void
    {
        $orderNo = $this->post('orderNo') ?: '';
        if (self::isNull($orderNo)) {
            $this->resp['warn'] = '单号不能为空';
        } else {
            // 调拨
            if (str_contains($orderNo, 'DB') === true) {
                $info = query('inventory_allot', " orderNo = '$orderNo' ");
                $source = 'inventoryAllot';
                $aliasName = '调拨单';
            } // 盘点
            elseif (str_contains($orderNo, 'PD') === true) {
                $info = query('inventory_take', " orderNo = '$orderNo' ");
                $source = 'inventoryTake';
                $aliasName = '盘点单';
            } else {
                $info = query('inventory', " orderNo = '$orderNo' ");
                $source = 'inventory';
                $aliasName = ($info['classify'] == 0) ? '出库单' : '入库单';
            }

            if (self::isNull($info['id'])) {
                $this->resp['warn'] = '单号信息不存在';
            } else {
                $data = [
                    'info'   => $info,
                    'source' => $source,
                    'from'   => $aliasName,
                ];
                $this->resp['data'] = $data;
                $this->code = 1;
            }
        }
    }

}
